package com.example.smartcitydemo.repo.bus

import com.example.smartcity_jscs.network.ResultStates.Resource
import com.example.smartcitydemo.base.BaseRepo
import com.example.smartcitydemo.bean.*
import com.example.smartcitydemo.exception.AppExcpetion
import com.example.smartcitydemo.exception.ErrorType
import com.example.smartcitydemo.network.api.AuthApiService
import com.example.smartcitydemo.network.api.NoAuthService
import com.example.smartcitydemo.network.client.NoAuthClient
import com.example.smartcitydemo.network.client.authApiService
import com.example.smartcitydemo.network.client.noAuthApiService
import com.example.smartcitydemo.repo.bus.BusRepo.postBusOrder
import com.example.smartcitydemo.ui.smartbus.bean.SmartBusExpanableData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import java.lang.RuntimeException

/**
 * @PACKAGE_NAME: com.example.smartcitydemo.repo.bus
 * @NAME: Caleb.F
 * @DATE: 2021/11/11 15:03
 * @Email: 1919796283@qq.com
 */
object BusRepo : BaseRepo() {
    suspend fun getBusOrder(statusId: Int): Flow<Resource<List<BusOrderInfo>>> {
        return requestListData({ authApiService.getBusOrder(statusId) }, { it })
    }

    suspend fun getParentData(): Flow<Resource<List<ParentBusStation>>> {
        return requestListData({ noAuthApiService.getLineParenData() }, { it })
    }

    suspend fun getChildData(list: List<Int>): Flow<Resource<Map<Int, List<ChildBusStation>>>> {
        return flow {
            //使用可变参数
            val map: MutableMap<Int, List<ChildBusStation>> = mutableMapOf()
            for (i in list) {
                val childLineData = noAuthApiService.getChildLineData(i)
                if (childLineData.code == 200) {
                    //成功则放入
                    map[childLineData.rows[0].linesId] = childLineData.rows
                }
            }
            if (map.size == 0) {
                throw AppExcpetion(ErrorType.NO_CONTENT_ERROR, RuntimeException("没有内容"))
            } else {
                emit(Resource.Success(map.toMap()))
            }

        }.catch { e ->
            throw  AppExcpetion.transFormException(e)
        }

    }


    /**
     * 使用操作符transform实现数据的变换,这边是同步还
     * @return Flow<Resource<List<SmartBusExpanableData>>>
     */
    suspend fun getSmartBusLineData(): Flow<Resource<List<SmartBusExpanableData>>> {
        val busListFlow = requestListData({ noAuthApiService.getBusList() }, { it })
        return busListFlow.transform { value ->
            emit(Resource.Loading())
            val dataMap = value.data?.associateBy {
                it.id
            }
            val list = mutableListOf<SmartBusExpanableData>()
            dataMap!!.keys.forEach { lineId ->
                val busStationDetail =
                    requestListData({ noAuthApiService.getBusStationDetail(lineId) }, { it })
                busStationDetail.collect {
                    if (it is Resource.Success) {
                        val smartBusExpanableData = SmartBusExpanableData(
                            parentData = dataMap.get(lineId)!!,
                            childData = it.data ?: mutableListOf()
                        )
                        list.add(smartBusExpanableData)
                        if (list.size == dataMap.size) {
                            emit(Resource.Success(list.toList()))
                        }
                    }
                }
            }
        }.flowOn(Dispatchers.IO)
    }

    suspend fun postBusOrder(bean: SmartBusRequestBean): Flow<Resource<BusOrderResponseBean>> {
        return flow {
            val netRequestResult = authApiService.postBusOrder(bean)
            if (netRequestResult.code == 200) {
                emit(Resource.Success(netRequestResult))
            } else {
                handleResponseErrorCode(netRequestResult.code, netRequestResult.msg)
            }
        }.flowOn(Dispatchers.IO)
    }
}